package awdc;
import java.net.*;
import java.io.*;

public class Speaker {
	private Socket s;

	private InputStream is;
	private OutputStream os;
	private int TimeOut = 1500;//Таймаут для установки сокета
	private int Tout = 1000;
	private String Address=null;
	//connect - метод, устанавливающий для сокета с соединение с сервером
	public int connect (String AddrAsStr, int port) {
		InetAddress AddrAsIAddr = null;
		//Определяем интернет адрес
		try {
			AddrAsIAddr = AddrAsIAddr.getByName(AddrAsStr);
		} catch (Exception e) {
			System.out.println("Could not get IP-address");
			return 1;
		};
		//Пытаемся на него законнектиться
		try {
			System.out.println("Try to connect to "+AddrAsIAddr+":"+port);
			//Ниже закомментировано, так как обновлено до коннекта без таймаута
			//s = new Socket (AddrAsIAddr, port);
			s = new Socket();
			//socket.setSoTimeout(1500);
			s.connect(new InetSocketAddress(AddrAsIAddr,port),TimeOut);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Could not establish socket!");
			return 1;
			//System.exit(-1);
		};
		try {
			is = s.getInputStream();
			os = s.getOutputStream();
		} catch (Exception e) {
			System.out.println("Some troubles with socket");
			return 1;
		};
		Address = AddrAsStr;
		return 0;
	};
	//receive
	public byte[] receive() {
		byte[] inputed = null;
		int count = 0;
		try {
			Thread.currentThread().sleep(Tout);
			count = is.available();	
			inputed = new byte[count];
		} catch (Exception e){
			System.out.println("Fuck!");
			e.printStackTrace();
		};
		try {
//			System.out.println("Try to read bytes from stream...");
			is.read(inputed);
		} catch (Exception e) {
			System.out.println("Can't read bytes from strem:(");
			e.printStackTrace();
		};
		String inputedString=null;
		try {
			inputedString = new String(inputed,"windows-1251");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Received from "+Address+":"+inputedString);
		return inputed;
	};
	public int send(byte[] output) {
		try {
			System.out.println("Send to: "+Address+":"+new String(output,"windows-1252"));
			os.write(output);
		} catch (Exception e) {
			System.out.println("Some troubles with sending data..");
			e.printStackTrace();
		};
		return 0;
	}
	public int send(String output) {
		try{
			System.out.println("Send to: "+Address+":"+output);
			os.write(output.getBytes("windows-1252"));
		} catch (Exception e) {
			System.out.println("Some troubles with sending data..");
			e.printStackTrace();
		};
		return 0;
	}



	public void disconnect() {
		try {
			s.close();
		} catch (Exception e) {
			System.out.println("Could not close socket..");
			e.printStackTrace();
		};
	}	
}
